﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZDSoft.QLMS.Entity;
using ZDSoft.QLMS.Web.Helpers;
using NHibernate.Criterion;
using ZDSoft.QLMS.Entity.QuestionLibrary;
using ZDSoft.QLMS.Entity.Rules;

namespace ZDSoft.QLMS.Web.Controllers
{
    public class TestPaperController : ControllerBase
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Create()
        {
            return View();
        }

        public ActionResult PerView()
        {
            return View();
        }

        public void CreateTestPaperByRuleID(int id, string name)
        {
            TestPaperRule tpr = new TestPaperRule().FindByID(id);
            Course course = tpr.Course;
            IList<TypeRule> typeRules = tpr.TypeRules;
            IList<ZDSoft.QLMS.Entity.Type> types = new List<ZDSoft.QLMS.Entity.Type>();

            TestPaper testPaper = new TestPaper();
            testPaper.Name = name;
            testPaper.Min = tpr.Min;
            testPaper.Course = tpr.Course;
            testPaper.score = tpr.Grade;
            testPaper.TestPaperParts = new List<TestPaperPart>();
            testPaper.Create();

            foreach (TypeRule tr in typeRules)
            {
                IList<KnowledgePoint> knowledgePoints = new List<KnowledgePoint>();
                ZDSoft.QLMS.Entity.Type type = tr.Type;

                TestPaperPart testPaperPart = new TestPaperPart();
                testPaperPart.Type = type;
                testPaperPart.score = testPaper.score * tr.Weight;
                testPaperPart.TestPaperMinParts = new List<TestPaperMinPart>();
                testPaperPart.TestPaper = testPaper;
                testPaperPart.Create();

                foreach (KnowledgePointRule kpr in tr.KnowledgePointRules)
                {
                    KnowledgePoint knowledgePoint = kpr.KnowledgePoint;
                    IList<DefficultDegree> defficultDegrees = new List<DefficultDegree>();
                    foreach (Detail dd in kpr.Details)
                    {
                        DefficultDegree defficultDegree = dd.DefficultDegree;
                        IList<ICriterion> queryConditions = new List<ICriterion>();
                        queryConditions.Add(Expression.Eq("Course", course));
                        queryConditions.Add(Expression.Eq("Type", type));
                        queryConditions.Add(Expression.Eq("Degree", defficultDegree));
                        queryConditions.Add(Expression.Eq("IsActive", true));
                        IList<Question> questions = new Question().Find(queryConditions);
                        IList<Question> realQuestions = new List<Question>();
                        int num = dd.Num;
                        for (int i = 0; i < num; i++)
                        {
                            realQuestions.Add(questions[i]);
                        }
                        TestPaperMinPart minPart = new TestPaperMinPart();
                        minPart.DefficultDegree = dd.DefficultDegree;
                        minPart.score = testPaper.score * tr.Weight * kpr.Weight * dd.Weight;
                        minPart.Questions = realQuestions;
                        minPart.TestPaperPart = testPaperPart;
                        minPart.Create();
                    }
                }
            }
        }

        public JsonResult GetAllChargeCourse()
        {
            IList<UserCourse> userCourses = AppHelper.LoginedUser.UserCourses;
            IList<Course> chargeCourses = new List<Course>();
            foreach (UserCourse uc in userCourses)
            {
                if (uc.IsCharge)
                {
                    chargeCourses.Add(uc.Course.ToJaonResult<Course>());
                }
            }
            return this.Json(chargeCourses, JsonRequestBehavior.AllowGet);
        }

        public string GetAllStrategyByCourseID(int id)
        {
            IList<ICriterion> queryConditions = new List<ICriterion>();
            queryConditions.Add(Expression.Eq("Course", new Course().FindByID(id)));
            IList<TestPaperRule> tprs = new TestPaperRule().Find(queryConditions);
            string jsonStr = "{\"tprIDs\":[";
            for (int i = 0; i < tprs.Count; i++)
            {
                jsonStr += "{\"id\":\"" + tprs[i].ID + "\"},";
            }
            jsonStr = jsonStr.Substring(0, jsonStr.Length - 1);
            jsonStr += "],";
            foreach (TestPaperRule tpr in tprs)
            {
                jsonStr += "\"" + tpr.ID + "\":[";
                foreach (TypeRule tr in tpr.TypeRules)
                {
                    jsonStr += "{\"weight\":\"" + tr.Weight + "\",\"id\":\"" + tr.ID + "\",\"tld\":\"tepy" + tr.Type.ID + "\",\"icon\":\"../../Content/img/diy/1_close.png\",\"name\":\"" + tr.Type.Name + "\"";
                    if (tr.KnowledgePointRules != null && tr.KnowledgePointRules.Count != 0)
                    {
                        jsonStr += ",\"children\":[";
                        foreach (KnowledgePointRule klp in tr.KnowledgePointRules)
                        {
                            jsonStr += "{\"weight\":\"" + klp.Weight + "\",\"id\":\"" + klp.ID + "\",\"tld\":\"know" + klp.KnowledgePoint.ID + "\",\"icon\":\"../../Content/img/diy/1_close.png\",\"name\":\"" + klp.KnowledgePoint.Name + "\"";
                            if (klp.Details != null && klp.Details.Count != 0)
                            {

                                jsonStr += ",\"children\":[";
                                foreach (Detail detail in klp.Details)
                                {
                                    jsonStr += "{\"weight\":\"" + detail.Weight + "\",\"id\":\"" + detail.ID + "\",\"tld\":\"diff" + (int)detail.DefficultDegree + "\",\"icon\":\"../../Content/img/diy/1_close.png\",\"name\":\"" + detail.DefficultDegree + "\"},";
                                }
                                jsonStr = jsonStr.Substring(0, jsonStr.Length - 1);
                                jsonStr += "]";
                            }
                            jsonStr += "},";
                        }
                        jsonStr = jsonStr.Substring(0, jsonStr.Length - 1);
                        jsonStr += "]";
                    }
                    jsonStr += "},";
                }
                jsonStr = jsonStr.Substring(0, jsonStr.Length - 1);
                jsonStr += "],";
            }
            jsonStr = jsonStr.Substring(0, jsonStr.Length - 1);
            jsonStr += "}";
            return jsonStr;
        }

        public string GetPaged(int pageIndex, int pageSize, string strSearchProperty,
            string strSearchCondition, string strSortProperty, string strSortCondition)
        {
            IList<ICriterion> queryConditions = new List<ICriterion>();
            IList<Order> orderList = new List<Order>();
            if (strSearchProperty != "")
            {
                string[] searchProperties = strSearchProperty.Split(',');
                string[] searchConditions = strSearchCondition.Split(',');
                queryConditions = new List<ICriterion>();
                for (int i = 0; i < searchProperties.Length; i++)
                {
                    queryConditions.Add(Expression.Eq(searchProperties[i], searchConditions[i]));
                }
            }
            if (strSortProperty != "")
            {
                string[] sortProperties = strSortProperty.Split(',');
                string[] sortConditions = strSortCondition.Split(',');
                orderList = new List<Order>();
                for (int i = 0; i < sortProperties.Length; i++)
                {
                    if (sortConditions[i] == "asc")
                    {
                        orderList.Add(new Order(sortProperties[i], true));
                    }
                    else
                    {
                        orderList.Add(new Order(sortProperties[i], false));
                    }
                }
            }
            int count;
            int pageNum;

            IList<TestPaper> list = new List<TestPaper>();
            IList<TestPaper> testPapers = new TestPaper().GetPaged(queryConditions, orderList, pageIndex, pageSize, out count);

            int tmpcountI = count / pageSize;
            float temCountF = float.Parse(count.ToString()) / float.Parse(pageSize.ToString());
            if (temCountF > float.Parse(tmpcountI.ToString()))
            {
                pageNum = tmpcountI + 1;
            }
            else
            {
                pageNum = tmpcountI;
            }
            if (testPapers.Count != 0 && testPapers != null)
            {
                string jsonStr = "[";
                foreach (TestPaper tp in testPapers)
                {
                    jsonStr += "{\"ID\":\"" + tp.ID + "\",\"name\":\"" + tp.Name + "\",\"course\":\"" + tp.Course.Name + "\",\"score\":\"" + tp.score + "\"},";
                }
                jsonStr += "{\"ID\":\"" + pageNum + "\"}";
                jsonStr += "]";
                return jsonStr;
            }
            else
            {
                return null;
            }
        }

        public string GetTestPaperHTMLByID(int id)
        {
            string[] strType = { "一丶", "二丶", "三丶", "四丶", "五丶" };
            TestPaper tp = new TestPaper().FindByID(id);
            string result = "";
            result += "<p>" + tp.Name + "</p>";
            result += "<p>考试时间：" + tp.Min + "分钟</p>";
            int i = 0;
            int num = 1;
            foreach (TestPaperPart tpp in tp.TestPaperParts)
            {
                result += "<p>" + strType[i] + tpp.Type.Name + ":共" + tpp.score + "分</p>";
                foreach (TestPaperMinPart tmp in tpp.TestPaperMinParts)
                {
                    foreach (Question q in tmp.Questions)
                    {
                        result += "<p>" + num + "." + q.Title + "</p>";
                        foreach (Answer answer in q.Answers)
                        {
                            result += "<p>" + answer.SerialNumber + "." + answer.Content+ "</p>";
                        }
                        num++;
                    }
                }
                i++;
            }
            return result;
        }

        public void Download(int id)
        {
            TestPaper testPaper = new TestPaper().FindByID(id);
            string result = "";
            result += testPaper.Name + ",";
            result += "考试时间：" + testPaper.Min + "分钟,";
            string[] strType = { "一丶", "二丶", "三丶", "四丶", "五丶" };
            int i = 0;
            int num = 1;
            foreach (TestPaperPart tpp in testPaper.TestPaperParts)
            {
                result += strType[i] + tpp.Type.Name + ":共" + tpp.score + "分,";
                foreach (TestPaperMinPart tmp in tpp.TestPaperMinParts)
                {
                    foreach (Question q in tmp.Questions)
                    {
                        result += num + "." + q.Title + ",";
                        foreach (Answer answer in q.Answers)
                        {
                            result += answer.SerialNumber + "." + answer.Content + ",";
                        }
                        num++;
                    }
                }
                i++;
            }
            result = result.Substring(0, result.Length - 1);
            DownLoadWord(result);
        }

        public void DownLoadWord(string str)
        {
            WordHelper word = new WordHelper();
            word.CreateAWord();
            IList<string> strList = str.Split(',');
            int flag = 0;
            string title = "";
            foreach (string i in strList)
            {
                if (flag == 0)
                {
                    title = i;
                    word.InsertText(i, 24, Microsoft.Office.Interop.Word.WdColor.wdColorBlack, 1, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter);
                    word.NewLine();
                }
                else if (flag == 1) {
                    word.InsertText(i, 14, Microsoft.Office.Interop.Word.WdColor.wdColorBlack, 1, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter);
                    word.NewLine();
                }
                else
                {
                    word.InsertText(i, 10, Microsoft.Office.Interop.Word.WdColor.wdColorBlack, 1, Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft);
                    word.NewLine();
                }
                flag++;
            }
            word.SaveWord(title);
        }
    }
}
